<template>
  <div>
    <en-table-layout
      toolbar
      pagination
      :tableData="tableData"
      :selectionChange="selectionChange"
      :loading="loading">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button @click="exportWinnerList">导出中奖名单</el-button>
          <el-button @click="showExchangeDialog">奖品兑换</el-button>
        </div>
        <div class="toolbar-search">
          <div class="search-select">
            <el-select v-model="searchForm.exchange_type" @change="changeWinnerType" clearable placeholder="兑奖方式">
              <el-option label="系统自动" value="0"></el-option>
              <el-option label="人工处理" value="1"></el-option>
            </el-select>
            <el-select v-model="searchForm.exchange_status" @change="changeWinnerStatus" clearable placeholder="兑奖状态" class="exchange_status">
              <el-option label="未兑奖" value="0"></el-option>
              <el-option label="已兑奖" value="1"></el-option>
            </el-select>
          </div>
          <en-table-search @search="searchEvent" placeholder="搜索关键字" />
        </div>
      </div>
      <template slot="table-columns">
        <el-table-column type="selection" width="50" fixed/>
        <el-table-column label="抽奖时间" width="120">
          <template slot-scope="scope">{{ scope.row.create_time | unixToDate('yyyy-MM-dd hh:mm') }}</template>
        </el-table-column>
        <el-table-column prop="member_nickname" label="抽奖用户"/>
        <el-table-column label="抽中奖品" prop="prize_name" width="120"/>
        <el-table-column label="奖品类型" prop="prize_type" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.prize_type === 1">实物奖品</span>
            <span v-if="scope.row.prize_type === 2">优惠券</span>
            <span v-if="scope.row.prize_type === 3">虚拟奖品</span>
            <span v-if="scope.row.prize_type === 4">谢谢参与</span>
          </template>
        </el-table-column>
        <el-table-column label="兑换方式" width="120">
          <template slot-scope="scope">
            <span>{{scope.row.exchange_type === 0? '系统自动': '人工处理'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="兑奖状态">
          <template slot-scope="scope">
            <span>{{scope.row.exchange_status === 0? '未兑奖': '已兑奖'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="兑奖时间">
          <template slot-scope="scope">{{ scope.row.exchange_time | unixToDate('yyyy-MM-dd hh:mm') }}</template>
        </el-table-column>
      </template>
      <el-pagination
        slot="pagination"
        v-if="pageData"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="pageData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.data_total">
      </el-pagination>
    </en-table-layout>
    <el-dialog
      title="奖品兑换"
      :visible.sync="exchangeDialog"
      width="400px">
      <el-form>
        <el-form-item label="奖品：">
          <span v-for="item in multipleChoice" class="prize-span">{{item.prize_name}}</span>
        </el-form-item>
        <el-form-item>
          <span class="exchange-tip">确定要兑换吗？</span>
        </el-form-item>
      </el-form>
      <div class="footer">
        <div class="infooter">
          <el-button type="primary" @click="exchangePrize()">确 定</el-button>
          <el-button @click="exchangeDialog=false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_prom from '@/api/promotion'

export default {
  name: 'winnerList',
  data() {
    return {
      /** 列表loading状态 */
      loading: false,
      // 多选
      multipleChoice: [],
      exchangeDialog: false,
      searchForm: {
        exchange_type: undefined,
        exchange_status: undefined
      },
      /** 列表参数 */
      params: {
        page_no: 1,
        page_size: 10
      },

      /** 列表数据 */
      tableData: null,

      /** 列表分页数据 */
      pageData: null
    }
  },
  created() {
    this.GET_DraftGoodsList()
  },
  methods: {
    // 多线
    selectionChange(value) {
      this.multipleChoice = value;
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_DraftGoodsList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_DraftGoodsList()
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      delete this.params.exchange_status;
      delete this.params.exchange_type;
      let _searchForm = JSON.parse(JSON.stringify(this.searchForm));
      for (const _key in _searchForm) {
        if (_searchForm[_key] === '') { // 当条件值为''时去除条件
          delete _searchForm[_key];
        }
      }
      this.params = {
        ...this.params,
        ..._searchForm,
        keyword: data
      }
      this.GET_DraftGoodsList()
    },

    /** 订单状态改变 */
    changeWinnerType(data) {
      delete this.params.keywords;
      // delete this.searchForm.exchange_status;
      this.params = {
        ...this.params,
        ...this.searchForm
      };
      this.GET_DraftGoodsList();
    },

    /** 订单状态改变 */
    changeWinnerStatus(data) {
      delete this.params.keywords;
      // delete this.searchForm.exchange_type;
      this.params = {
        ...this.params,
        ...this.searchForm
      };
      this.GET_DraftGoodsList();
    },

    GET_DraftGoodsList() {
      // this.loading = true
      let luchId = this.$route.params.luck_id
      this.params.luck_id = luchId
      API_prom.queryLuckRecordList(this.params).then(response => {
        console.log(response)
        this.loading = false
        this.pageData = {
          page_no: response.page_no,
          page_size: response.page_size,
          data_total: response.data_total
        }
        this.tableData = response.data
      }).catch((err) => {
        this.$message.error(err.message);
      })
    },

    exchangePrize() {
      // this.loading = true
      let params = []
      this.multipleChoice.forEach((item) => {
        params.push(item.luck_record_id)
      })
      params = params.join(',') 
      API_prom.exchangePrize({ luckRecordIds: params }).then(response => {
        this.$message.success(response.message);
        this.exchangeDialog = false
        this.GET_DraftGoodsList()
      }).catch((err) => {
        console.log('err:', err)
      })
    },
    showExchangeDialog() {
      if (this.multipleChoice.length === 0) {
        this.$message.error('请选择要兑换的奖品！')
        return
      }
      let flag = true
      this.multipleChoice.forEach((item) => {
        if (item.exchange_status === 1) {
          this.$message.error('选择的奖品中存在已兑换的奖品！')
          flag = false
        }
      })
      if (flag) {
        this.exchangeDialog = true
      }
    },

    exportWinnerList() {
      API_prom.luckRecordExport(this.params).then(response => {
        console.log(response)
        // 处理返回的文件流
        let blob = new Blob([response], {
          type: 'application/vnd.ms-excel;charset=utf-8'
        });
        let date = new Date().getFullYear() + '' + (new Date().getMonth() + 1) + '-' + new Date().getDate();
        const fileName = date + name + '中奖名单.xlsx';
        if ('download' in document.createElement('a')) {
          // 非IE下载
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      }).catch((err) => {
        console.log('err:', err)
      })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
  /deep/ .el-table td:not(.is-left) {
    text-align: center;
  }

  /** 工具条 */
  /deep/ div.toolbar {
    height: 70px;
    padding: 20px 0;
  }
  .inner-toolbar {
    display: flex;
    width: 100%;
    justify-content: space-between;
    .toolbar-btns {
      span {
        display: inline-block;
        font-size: 14px;
        color: #606266;
      }
    }
    .toolbar-search {
      margin-right: 10px;
      display: flex;
    }
    .search-select {
      margin-right: 10px;
    }
    .exchange_status {
      margin-left: 5px;
    }
  }

  /*商品图片*/
  .goods-image {
    width: 50px;
    height: 50px;
  }
.footer {
  display: flex;
  justify-content: center;
}
.prize-span {
  margin-right: 10px;
  border: 1px solid #999;
  padding: 5px 10px;
}

</style>
